import React, { useEffect, useState } from 'react';
import { Switch, Button, List, Skeleton, Image, Space } from 'antd';
import styles from './bannerList.module.less';
import { axios_GetBanner, axios_DelBanner, axios_UpdateBanner } from '../service.js';

// 获取轮播图列表数据
const getBannerData = async () => {
  let { code, data, message } = await axios_GetBanner() || {};
  if (code!=="200") {
      return alert(`${message}`);
  }
  localStorage.setItem("bannerData", JSON.stringify(data));
};

// 删除轮播图
const delBannerData = async (bannerid) => {
  let { code, message } = await axios_DelBanner({bannerid}) || {};
  if (code!=="200") {
      return alert(`${message}`);
  }
  getBannerData();
};

// 获取轮播图状态
const updateBannerData = async (bannerid,flag) => {
  let { code, message } = await axios_UpdateBanner(bannerid,flag) || {};
  if (code!=="200") {
      return alert(`${message}`);
  }
  getBannerData();
};

const BannerList = () => {
  const [initLoading, setInitLoading] = useState(true);
  const [list, setList] = useState([]);
  useEffect(() => {
    getBannerData();
    setInitLoading(false);
    setList(JSON.parse(window.localStorage.getItem('bannerData')));
  }, []);
    // fetch(fakeDataUrl)
    //   .then((res) => res.json())
    //   .then((res) => {
    //     const newData = data.concat(res.results);
    //     setData(newData);
    //     setList(newData);
    //     setLoading(false);
    //     window.dispatchEvent(new Event('resize'));
    //   });
  return (
    <List
      className={styles.demo_loadmore_list}
      loading={initLoading}
      itemLayout="horizontal"
      dataSource={list}
      renderItem={(item) => (
        <List.Item
          actions={[<Switch checked={item.flag} onChange={()=>{updateBannerData(item.bannerid,!item.flag)}} checkedChildren="展示" unCheckedChildren="撤除" defaultChecked />, <Button key="list-loadmore-more" onClick={()=>{
            delBannerData(item.bannerid)
          }}>删除</Button>]}
        >
          <Skeleton avatar title={false} loading={item.loading} active>
            <List.Item.Meta
              avatar={
              <Space size={12}>
                <Image
                  width={80}
                  height={80}
                  src={item.link}
                  placeholder={
                    <Image
                      preview={false}
                      src={item.link}
                      width={80}
                      height={80}
                    />
                  }
                />
              </Space>}
              title={<span>{item.alt}</span>}
            />
          </Skeleton>
        </List.Item>
      )}
    />
  );
};
export default BannerList;